package com.jeecg.teamrank.main.web.back;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jeecgframework.minidao.pojo.MiniDaoPage;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.page.SystemTools;
import org.jeecgframework.p3.core.util.PropertiesUtil;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import com.jeecg.teamrank.main.entity.JpTeamPerson;
import com.jeecg.teamrank.main.service.JpTeamPersonService;
import com.jeecg.teamrank.main.util.ConfigUtil;

 /**
 * 描述：</b>TSTeamPersonController<br>
 * @author p3.jeecg
 * @since：2016年06月30日 11时19分16秒 星期四 
 * @version:1.0
 */
@Controller
@RequestMapping("/teamrank/jpTeamPerson")
public class JpTeamPersonController extends BaseController{
  @Autowired
  private JpTeamPersonService jpTeamPersonService;
  
	/**
	  * 列表页面
	  * @return
	  */
	@RequestMapping(params = "list",method = {RequestMethod.GET,RequestMethod.POST})
	public void list(@ModelAttribute JpTeamPerson query,HttpServletRequest request,HttpServletResponse response,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
			try {
			 	LOG.info(request, " back list");
			 	//分页数据
				MiniDaoPage<JpTeamPerson> list =  jpTeamPersonService.getAll(query,pageNo,pageSize);
				VelocityContext velocityContext = new VelocityContext();
				 String img_domain = ConfigUtil.getProperty("img_domain"); 
				 velocityContext.put("img_domain", img_domain);
				velocityContext.put("jpTeamPerson",query);
				velocityContext.put("pageInfos",SystemTools.convertPaginatedList(list));
				String viewName = "teamrank/main/back/jpTeamPerson-list.vm";
				ViewVelocity.view(request,response,viewName,velocityContext);
			} catch (Exception e) {
			e.printStackTrace();
			}
}

	 /**
	  * 详情
	  * @return
	  */
	@RequestMapping(params="toDetail",method = RequestMethod.GET)
	public void jpTeamPersonDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request)throws Exception{
			VelocityContext velocityContext = new VelocityContext();
			String viewName = "teamrank/main/back/jpTeamPerson-detail.vm";
			JpTeamPerson jpTeamPerson = jpTeamPersonService.get(id);
			velocityContext.put("jpTeamPerson",jpTeamPerson);
			ViewVelocity.view(request,response,viewName,velocityContext);
	}

	/**
	 * 跳转到添加页面
	 * @return
	 */
	@RequestMapping(params = "toAdd",method ={RequestMethod.GET, RequestMethod.POST})
	public void toAddDialog(HttpServletRequest request,HttpServletResponse response)throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 String img_domain = ConfigUtil.getProperty("img_domain");
		 velocityContext.put("img_domain", img_domain);
		 String viewName = "teamrank/main/back/jpTeamPerson-add.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
	}

	/**
	 * 保存信息
	 * @return
	 */
	@RequestMapping(params = "doAdd",method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson doAdd(@ModelAttribute JpTeamPerson jpTeamPerson){
		AjaxJson j = new AjaxJson();
		try {
		    String randomSeed = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
		    jpTeamPerson.setId(randomSeed);
			jpTeamPersonService.insert(jpTeamPerson);
			j.setMsg("保存成功");
		} catch (Exception e) {
		    log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("保存失败");
		}
		return j;
	}

	/**
	 * 跳转到编辑页面
	 * @return
	 */
	@RequestMapping(params="toEdit",method = RequestMethod.GET)
	public void toEdit(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request) throws Exception{
			 VelocityContext velocityContext = new VelocityContext();	
			 JpTeamPerson jpTeamPerson = jpTeamPersonService.get(id);
			 String img_domain = ConfigUtil.getProperty("img_domain"); 
			 velocityContext.put("img_domain", img_domain);
			 velocityContext.put("jpTeamPerson",jpTeamPerson);
			 String viewName = "teamrank/main/back/jpTeamPerson-edit.vm";
			 ViewVelocity.view(request,response,viewName,velocityContext);
	}

	/**
	 * 编辑
	 * @return
	 */
	@RequestMapping(params = "doEdit",method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson doEdit(@ModelAttribute JpTeamPerson jpTeamPerson){
		AjaxJson j = new AjaxJson();
		try {
			jpTeamPersonService.update(jpTeamPerson);
			j.setMsg("编辑成功");
		} catch (Exception e) {
		    log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("编辑失败");
		}
		return j;
	}
	/**
	 * 删除
	 * @return
	 */
	@RequestMapping(params="doDelete",method = RequestMethod.GET)
	@ResponseBody
	public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) String id){
			AjaxJson j = new AjaxJson();
			try {
				JpTeamPerson jpTeamPerson = new JpTeamPerson();
				jpTeamPerson.setId(id);
				jpTeamPersonService.delete(jpTeamPerson);
				j.setMsg("删除成功");
			} catch (Exception e) {
			    log.info(e.getMessage());
				j.setSuccess(false);
				j.setMsg("删除失败");
			}
			return j;
	}

	/**
	 * 上传图片
	 * 
	 */
	@RequestMapping(value = "doUpload",method ={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public AjaxJson doUpload(MultipartHttpServletRequest request,HttpServletResponse response){
		AjaxJson j = new AjaxJson();
		try {
			String randomSeed = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
			MultipartFile uploadify = request.getFile("file");
	        byte[] bytes = uploadify.getBytes();  
	        String realFilename=uploadify.getOriginalFilename();
	        String subsimage= realFilename.substring(realFilename.length()-4, realFilename.length());
			Date date =new Date();
			SimpleDateFormat formater = new SimpleDateFormat();  
	        formater.applyPattern("yyyy/MM/dd"); 
	        String dt = formater.format(date).toString();
			String imgurl=dt+"/"+randomSeed+ subsimage;
			String Root=ConfigUtil.getProperty("img_upload_path");
			File dir = new File(Root+"/"+imgurl);//定义文件存储路径
			System.out.println(dir);
			if (!dir.exists()){
				dir.mkdirs();
			}
			uploadify.transferTo(dir);//上传文件到存储路径
			
	        j.setObj(imgurl);
	        j.setSuccess(true);
			j.setMsg("保存成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("保存失败");
		}
		System.out.println(j.getObj());
		return j;
	}
	
	/**
	 * 加载图片
	 * @param response
	 * @param imgUrl
	 * @throws IOException
	 */
	private void getImg(HttpServletResponse response,String imgUrl)  
	        throws IOException {  
	    FileInputStream fis = null;  
	    OutputStream os = null;  
	    try {
	    	File file=new File(imgUrl);
	    	if(!file.exists()){
	    		return;
	    	}
	        fis = new FileInputStream(file);  
	        os = response.getOutputStream();  
	        int count = 0;  
	        byte[] buffer = new byte[1024 * 8];  
	        while ((count = fis.read(buffer)) != -1) {  
	            os.write(buffer, 0, count);  
	            os.flush();  
	        }  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    } finally {  
	        if(fis!=null)
	        	fis.close();
	        if(os!=null)
	        	os.close();
	    }  
	} 
	//加载图片
	@RequestMapping(params="getImgUrl",method ={RequestMethod.POST,RequestMethod.GET})
	public void getImgUrl(HttpServletResponse response,HttpServletRequest request) {  
		String imgurl = request.getParameter("imgurl");
		try {
			if(imgurl!=null){
			String Root=ConfigUtil.getProperty("img_upload_path");
			imgurl=Root+"/"+imgurl;
				if(StringUtils.isEmpty(imgurl))
					{
						return;
					}
					getImg(response,imgurl);
				}else{
					return ;
				}
		} catch (IOException e) {
			//
		}
	} 
	
	
	
	private String getFileBasePath(HttpServletRequest request) {
		// String basePath =
		// request.getSession().getServletContext().getRealPath("upload/");
		PropertiesUtil p = new PropertiesUtil("pxconfig.properties");
		String basePath = p.readProperty("pms.rc.file.path");
		return basePath;
	}
	

}

